package com.bookworld.model;

import jakarta.validation.constraints.*;
import org.springframework.format.annotation.NumberFormat;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

public class Cart {
    private Long id;
    
    @NotNull(message = "{cart.user.notnull}")
    private Long userId;
    
    @NotBlank(message = "{cart.sessionId.notblank}")
    private String sessionId;
    
    @NotNull(message = "{cart.totalAmount.notnull}")
    @DecimalMin(value = "0.00", message = "{cart.totalAmount.min}")
    @NumberFormat(pattern = "#,##0.00")
    private BigDecimal totalAmount;
    
    @DecimalMin(value = "0.00", message = "{cart.discount.min}")
    private BigDecimal discount;
    
    @NotNull(message = "{cart.finalAmount.notnull}")
    @DecimalMin(value = "0.00", message = "{cart.finalAmount.min}")
    private BigDecimal finalAmount;
    
    @NotNull(message = "{cart.itemCount.notnull}")
    @Min(value = 0, message = "{cart.itemCount.min}")
    private Integer itemCount;
    
    private Boolean active;
    
    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;
    private LocalDateTime expiresAt;
    
    // 关联对象
    private User user;
    private List<CartItem> items;

    public Cart() {
        this.totalAmount = BigDecimal.ZERO;
        this.discount = BigDecimal.ZERO;
        this.finalAmount = BigDecimal.ZERO;
        this.itemCount = 0;
        this.active = true;
        this.createdAt = LocalDateTime.now();
    }

    // 计算总金额
    public void calculateTotal() {
        BigDecimal total = BigDecimal.ZERO;
        int count = 0;
        
        if (items != null) {
            for (CartItem item : items) {
                total = total.add(item.getSubtotal());
                count += item.getQuantity();
            }
        }
        
        this.totalAmount = total;
        this.itemCount = count;
        this.finalAmount = total.subtract(discount);
    }

    // 添加商品
    public void addItem(CartItem item) {
        if (items != null) {
            boolean found = false;
            for (CartItem existingItem : items) {
                if (existingItem.getBookId().equals(item.getBookId())) {
                    existingItem.setQuantity(existingItem.getQuantity() + item.getQuantity());
                    found = true;
                    break;
                }
            }
            if (!found) {
                items.add(item);
            }
        }
        calculateTotal();
    }

    // 移除商品
    public void removeItem(Long bookId) {
        if (items != null) {
            items.removeIf(item -> item.getBookId().equals(bookId));
        }
        calculateTotal();
    }

    // 清空购物车
    public void clear() {
        if (items != null) {
            items.clear();
        }
        calculateTotal();
    }

    // 检查是否过期
    public boolean isExpired() {
        return expiresAt != null && LocalDateTime.now().isAfter(expiresAt);
    }

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public BigDecimal getTotalAmount() {
        return totalAmount;
    }

    public void setTotalAmount(BigDecimal totalAmount) {
        this.totalAmount = totalAmount;
    }

    public BigDecimal getDiscount() {
        return discount;
    }

    public void setDiscount(BigDecimal discount) {
        this.discount = discount;
    }

    public BigDecimal getFinalAmount() {
        return finalAmount;
    }

    public void setFinalAmount(BigDecimal finalAmount) {
        this.finalAmount = finalAmount;
    }

    public Integer getItemCount() {
        return itemCount;
    }

    public void setItemCount(Integer itemCount) {
        this.itemCount = itemCount;
    }

    public Boolean getActive() {
        return active;
    }

    public void setActive(Boolean active) {
        this.active = active;
    }

    public LocalDateTime getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(LocalDateTime createdAt) {
        this.createdAt = createdAt;
    }

    public LocalDateTime getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(LocalDateTime updatedAt) {
        this.updatedAt = updatedAt;
    }

    public LocalDateTime getExpiresAt() {
        return expiresAt;
    }

    public void setExpiresAt(LocalDateTime expiresAt) {
        this.expiresAt = expiresAt;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<CartItem> getItems() {
        return items;
    }

    public void setItems(List<CartItem> items) {
        this.items = items;
    }

    @Override
    public String toString() {
        return "Cart{" +
                "id=" + id +
                ", userId=" + userId +
                ", sessionId='" + sessionId + '\'' +
                ", totalAmount=" + totalAmount +
                ", itemCount=" + itemCount +
                ", active=" + active +
                '}';
    }
}
